package com.fulihui.wgj.service.wx48;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fulihui.common.builder.rpc.RpcResultBuilder;
import com.fulihui.common.conv.BeanConv;
import com.fulihui.common.enums.ContainOrEliminateEnum;
import com.fulihui.common.enums.SendLogStatusEnum;
import com.fulihui.common.enums.Wx48UseTypeEnum;
import com.fulihui.common.error.Errors;
import com.fulihui.common.error.InvokeServiceException;
import com.fulihui.common.request.rpc.AppRequest;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.result.rpc.SimpleResult;
import com.fulihui.common.util.ConditionValidator;
import com.fulihui.common.util.DateUtils;
import com.fulihui.common.util.JedisUtil;
import com.fulihui.weixinsdk.model.Article;
import com.fulihui.weixinsdk.model.NewsMessage;
import com.fulihui.wgj.dal.mybatis.domain.Wx48Attention;
import com.fulihui.wgj.dal.mybatis.domain.Wx48NewsInfo;
import com.fulihui.wgj.dal.mybatis.domain.Wx48NewsLog;
import com.fulihui.wgj.dal.mybatis.repository.Wx48AttentionRepository;
import com.fulihui.wgj.dal.mybatis.repository.Wx48NewsInfoRepository;
import com.fulihui.wgj.dal.mybatis.repository.Wx48NewsLogRepository;
import com.fulihui.wgj.dal.mybatis.repository.WxSubscribeReplyRuleRepository;
import com.fulihui.wgj.facade.dto.Wx48MsgDTO;
import com.fulihui.wgj.facade.dto.Wx48NewsInfoDTO;
import com.fulihui.wgj.facade.dto.Wx48NewsLogDTO;
import com.fulihui.wgj.facade.msg.Wx48HMsg;
import com.fulihui.wgj.facade.request.wx48.Wx48AttentionSaveRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsCrowdRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsInfoPageQueryRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsInfoSaveRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsLogCancelRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsLogPageQueryRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsLogQueryRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsLogSaveRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsLogUpdateAccumRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsLogUpdateRequest;
import com.fulihui.wgj.facade.request.wx48.Wx48NewsSendRequest;
import com.fulihui.wgj.facade.result.wx48.Wx48NewsInfoPageResult;
import com.fulihui.wgj.facade.result.wx48.Wx48NewsLogPageResult;
import com.fulihui.wgj.facade.service.wx48.Wx48NewsInfoService;
import com.fulihui.wgj.mq.kafka.producer.KafkaProducer;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author wang_wx
 * @date 2018-07-03
 */
@Component
@Service(interfaceClass = Wx48NewsInfoService.class, version = "1.0.0", timeout = 5000)
public class Wx48NewsInfoServiceImpl implements Wx48NewsInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(Wx48NewsInfoServiceImpl.class);

    /**
     * 48小时发送到队列的内容redis 前缀
     */
    private static final String WX48_NEWS_INFO_SEND_REDIS_PREFIX = "WX48_SEND_REDIS_";

    /**
     * 队列批次长度--一般
     */
    public static final int MQ_LENGTH_GENERALLY = 200;

    @Autowired
    WxSubscribeReplyRuleRepository wxSubscribeReplyRuleRepository;

    @Autowired
    Wx48NewsInfoRepository wx48NewsInfoRepository;

    @Autowired
    Wx48NewsLogRepository wx48NewsLogRepository;

    @Autowired
    Wx48AttentionRepository wx48AttentionRepository;

    @Autowired
    KafkaProducer kafkaProducer;

    @Autowired
    JedisUtil jedisUtil;

    @Override
    public BaseResult saveAttention(Wx48AttentionSaveRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);
        Wx48Attention wx48Attention = BeanConv.copy(request, Wx48Attention.class);
        Wx48Attention wx48AttentionQuery = new Wx48Attention();
        wx48AttentionQuery.setOpenid(wx48Attention.getOpenid());
        Wx48Attention queryOne = wx48AttentionRepository.queryOne(wx48AttentionQuery);
        int count;
        if (Objects.isNull(queryOne)) {
            count = wx48AttentionRepository.saveSelective(wx48Attention);
        } else {
            queryOne.setGmtModified(new Date());
            count = wx48AttentionRepository.updateSelective(queryOne);
        }
        return count > 0 ? RpcResultBuilder.succ() : RpcResultBuilder.fail(Errors.Commons.SAVE_FAILED);
    }

    @Override
    public SimpleResult<String> deleteByLessModified(Date exceedTime) {
        if (Objects.isNull(exceedTime)) {
            return RpcResultBuilder.failSimple(Errors.Commons.REQUEST_PARAMETER_ERROR);
        }
        Integer count = wx48AttentionRepository.deleteByLessModified(exceedTime);
        SimpleResult<String> result = RpcResultBuilder.succSimple(String.valueOf(count));
        return result;
    }

    @Override
    public SimpleResult<Wx48NewsInfoDTO> querySpecificReply(AppRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);
        Wx48NewsInfo wx48NewsInfo = wx48NewsInfoRepository.querySpecificReply(request.getAppId());
        Wx48NewsInfoDTO newsInfoDTO = null;
        if (Objects.nonNull(wx48NewsInfo)) {
            newsInfoDTO = BeanConv.copy(wx48NewsInfo, Wx48NewsInfoDTO.class);
        }
        return RpcResultBuilder.succSimple(newsInfoDTO);
    }

    @Override
    public Wx48NewsInfoPageResult pageQueryNewsInfo(Wx48NewsInfoPageQueryRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);
        PageInfo<Wx48NewsInfo> pageInfo = wx48NewsInfoRepository.queryPageListByRequest(request);
        long total = pageInfo.getTotal();
        Wx48NewsInfoPageResult result = RpcResultBuilder.succPageResult(Wx48NewsInfoPageResult.class, pageInfo.getPageNum(), pageInfo.getPageSize(), Math.toIntExact(total));
        if (total > 0) {
            result.setValue(BeanConv.copy(pageInfo.getList(), Wx48NewsInfoDTO.class));
        }
        return result;
    }

    @Transactional(value = "mysqlTransactionManager", rollbackFor = Exception.class)
    @Override
    public SimpleResult<Long> saveNewsInfo(Wx48NewsInfoSaveRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);
        Long useType = request.getUseType();
        // 用途 默认一般
        if (Objects.isNull(useType)) {
            useType = Wx48UseTypeEnum.general.getValue();
        }
        Wx48NewsInfo wx48NewsInfo = BeanConv.copy(request, Wx48NewsInfo.class);
        Long id = wx48NewsInfo.getId();
        int count;
        if (Wx48UseTypeEnum.specificReply.getValue() == useType) {
            //如果类型是特定回复 保证只能有一条 故先把所有类型更改为一般
            wx48NewsInfoRepository.updateUseType2New(request.getAppId(), useType, Wx48UseTypeEnum.general.getValue());
        }
        if (Objects.isNull(id)) {
            count = wx48NewsInfoRepository.saveSelective(wx48NewsInfo);
        } else {
            wx48NewsInfo.setGmtModified(new Date());
            count = wx48NewsInfoRepository.updateSelective(wx48NewsInfo);
        }
        return count > 0 ? RpcResultBuilder.succSimple(wx48NewsInfo.getId()) : RpcResultBuilder.failSimple(Errors.Commons.SAVE_FAILED);
    }

    @Override
    public SimpleResult<String> countSendWx48News(Wx48NewsCrowdRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);

        // 清除不属于48小时的用户
//        Integer delete = wx48AttentionRepository.deleteByLessModified(DateUtils.addHours(new Date(), -48));
//        LOGGER.info("清除48小时的用户数量{}", delete);

        // 查询推送人数
        Integer records = wx48AttentionRepository.countByExample(buildCrowdExample(request));
        LOGGER.info("WEIXIN48H-计算推送人数，records={}", records);
        return RpcResultBuilder.succSimple(Objects.isNull(records) ? "0" : String.valueOf(records));
    }

    @Transactional(value = "mysqlTransactionManager", rollbackFor = Exception.class)
    @Override
    public BaseResult sendWx48News(Wx48NewsLogSaveRequest wx48NewsLogSaveRequest) throws InvokeServiceException {
        ConditionValidator.validate(wx48NewsLogSaveRequest);

        Wx48NewsCrowdRequest wx48NewsCrowdRequest = wx48NewsLogSaveRequest.getWx48NewsCrowdRequest();

        // 查询是否有图文信息
        Long newsId = wx48NewsLogSaveRequest.getNewsId();
        Wx48NewsInfo wx48NewsInfo = wx48NewsInfoRepository.queryById(newsId);
        if (Objects.isNull(wx48NewsInfo) && StringUtils.isBlank(wx48NewsInfo.getXmlContent())) {
            LOGGER.info("WEIXIN48H-未查询到图文信息，id={}", newsId);
            return RpcResultBuilder.fail(Errors.Wx48HError.WX48_HOURS_MESSAGE_NOT_FOUND);
        }

        // 清除不属于48小时的用户
        Integer delete = wx48AttentionRepository.deleteByLessModified(DateUtils.addHours(new Date(), -48));
        LOGGER.info("清除48小时的用户数量{}", delete);

        // 查询推送人数
        Integer records = wx48AttentionRepository.countByExample(buildCrowdExample(wx48NewsCrowdRequest));
        LOGGER.info("WEIXIN48H-初始化推送人数，records={}", records);
        if (0 >= records) {
            return RpcResultBuilder.fail(Errors.Wx48HError.THE_CURRENT_APP_PUSHES_RECORD_EMPTY);
        }

        // 插入发送记录表
        Long recordId = insertWx48News(wx48NewsLogSaveRequest, wx48NewsCrowdRequest, records);
        if (Objects.isNull(recordId)) {
            return RpcResultBuilder.fail(Errors.Commons.SAVE_FAILED);
        }

        // 发送48小时图文消息存进redis中供发送方使用
        String xmlContent = wx48NewsInfo.getXmlContent();
        NewsMessage newsMessage = JSON.parseObject(xmlContent, NewsMessage.class);
        String msgtype = newsMessage.getMsgtype();
        List<Article> articles = newsMessage.getNews().getArticles();
        Wx48MsgDTO wx48MsgDTO = new Wx48MsgDTO();
        wx48MsgDTO.setMsgtype(msgtype);
        Map<String, List<Article>> news = Maps.newHashMap();
        news.put("articles", articles);
        wx48MsgDTO.setNews(news);
        jedisUtil.set(WX48_NEWS_INFO_SEND_REDIS_PREFIX + newsId, JSON.toJSONString(wx48MsgDTO));

        // 发送逻辑
        Date jobTime = wx48NewsLogSaveRequest.getJobTime();
        if (Objects.isNull(jobTime)) {
            // 不是定时任务 立即发送
            Wx48NewsSendRequest wx48NewsSendRequest = new Wx48NewsSendRequest();
            wx48NewsSendRequest.setAppId(wx48NewsLogSaveRequest.getAppId());
            wx48NewsSendRequest.setNewId(newsId);
            wx48NewsSendRequest.setRecordId(recordId);
            wx48NewsSendRequest.setWx48NewsCrowdRequest(wx48NewsCrowdRequest);
            this.sendWx48NewsTask(wx48NewsSendRequest);
        } else {
            // 是定时任务
        }

        return RpcResultBuilder.succ();
    }

    @Override
    public BaseResult sendWx48NewsTask(Wx48NewsSendRequest request) throws InvokeServiceException {
        // 查询推送人数
        Integer records = wx48AttentionRepository.countByExample(buildCrowdExample(request.getWx48NewsCrowdRequest()));
        LOGGER.info("WEIXIN48H-初始化推送人数，records={}", records);
        if (0 >= records) {
            return RpcResultBuilder.fail(Errors.Wx48HError.THE_CURRENT_APP_PUSHES_RECORD_EMPTY);
        }
        // 初始化推送人数
        Wx48NewsLog wx48NewsLog = new Wx48NewsLog();
        wx48NewsLog.setId(request.getRecordId());
        wx48NewsLog.setStatus(SendLogStatusEnum.pushing.getCode());
        wx48NewsLog.setSendCount(Long.valueOf(records));
        wx48NewsLog.setSendStartTime(new Date());
        wx48NewsLogRepository.updateSelective(wx48NewsLog);

        // 发送队列
        Wx48HMsg wx48HMsg = new Wx48HMsg();
        wx48HMsg.setAppId(request.getAppId());
        wx48HMsg.setRecordId(request.getRecordId());
        wx48HMsg.setNewsKey(WX48_NEWS_INFO_SEND_REDIS_PREFIX + request.getNewId());
        //  每页条数
        int pageSize = 2000;
        // 页码
        int pageCount = (records + pageSize - 1) / pageSize;
        boolean isLastPage = false;
        for (int pageNum = 1; pageNum <= pageCount; pageNum++) {
            if (pageNum == pageCount) {
                isLastPage = true;
            }
            PageInfo<Wx48Attention> pageInfo = wx48AttentionRepository.queryPageListByExample(buildCrowdExample(request.getWx48NewsCrowdRequest()), pageNum, pageSize);
            List<Wx48Attention> wx48Attentions = pageInfo.getList();
            if (!CollectionUtils.isEmpty(wx48Attentions)) {
                List<String> openIds = Lists.newArrayList();
                wx48Attentions.stream().forEach(wx48Attention -> openIds.add(wx48Attention.getOpenid()));
                putMsg2MQ(openIds, isLastPage, wx48HMsg);
            }
        }
        return RpcResultBuilder.succ();
    }

    /**
     * 组装消息队列
     *
     * @param openIdList
     * @param isLastPage
     * @param wx48HMsg
     */
    private void putMsg2MQ(List<String> openIdList, boolean isLastPage, Wx48HMsg wx48HMsg) {
        LOGGER.info("WEIXIN48H-put weixin 48h msg to MQ....");
        //复制一个新的对象到MQ
        Wx48HMsg weixin48MsgNew = new Wx48HMsg();
        BeanUtils.copyProperties(wx48HMsg, weixin48MsgNew);
        weixin48MsgNew.setLast(isLastPage);

        // 按100条分割一份 扔队列
        List<List<String>> partition = Lists.partition(openIdList, MQ_LENGTH_GENERALLY);
        partition.stream().forEach(strings -> {
            weixin48MsgNew.setOpenIds(strings);
            kafkaProducer.sendWx48hMsg(weixin48MsgNew);
        });
    }

    private Example buildCrowdExample(Wx48NewsCrowdRequest wx48NewsCrowdRequest) {
        if (Objects.isNull(wx48NewsCrowdRequest)) {
            return null;
        }
        Example example = new Example(Wx48Attention.class);
        Example.Criteria criteria = example.createCriteria();
        String appId = wx48NewsCrowdRequest.getAppId();
        String sexTab = wx48NewsCrowdRequest.getSexTab();
        Integer sex = wx48NewsCrowdRequest.getSex();
        String countryTab = wx48NewsCrowdRequest.getCountryTab();
        String country = wx48NewsCrowdRequest.getCountry();
        String provinceTab = wx48NewsCrowdRequest.getProvinceTab();
        String province = wx48NewsCrowdRequest.getProvince();
        String cityTab = wx48NewsCrowdRequest.getCityTab();
        String city = wx48NewsCrowdRequest.getCity();
        Date subscribeTimeStart = wx48NewsCrowdRequest.getSubscribeTimeStart();
        Date subscribeTimeEnd = wx48NewsCrowdRequest.getSubscribeTimeEnd();
        criteria.andEqualTo("appId", appId);
        if (null != sex) {
            if (ContainOrEliminateEnum.CONTAIN.getCode().equals(sexTab)) {
                criteria.andEqualTo("sex", sex);
            } else {
                criteria.andNotEqualTo("sex", sex);
            }
        }
        if (StringUtils.isNotBlank(country)) {
            List<String> countryList = Splitter.on(",").splitToList(country);
            if (ContainOrEliminateEnum.CONTAIN.getCode().equals(countryTab)) {
                criteria.andIn("country", countryList);
            } else {
                criteria.andNotIn("country", countryList);
            }
        }
        if (StringUtils.isNotBlank(province)) {
            List<String> provinceList = Splitter.on(",").splitToList(province);
            if (ContainOrEliminateEnum.CONTAIN.getCode().equals(provinceTab)) {
                criteria.andIn("province", provinceList);
            } else {
                criteria.andNotIn("province", provinceList);
            }
        }
        if (StringUtils.isNotBlank(city)) {
            List<String> cityList = Splitter.on(",").splitToList(city);
            if (ContainOrEliminateEnum.CONTAIN.getCode().equals(cityTab)) {
                criteria.andIn("city", cityList);
            } else {
                criteria.andNotIn("city", cityList);
            }
        }
        if (Objects.nonNull(subscribeTimeStart)) {
            criteria.andGreaterThanOrEqualTo("gmt_modified", subscribeTimeStart);
        }
        if (Objects.nonNull(subscribeTimeEnd)) {
            criteria.andGreaterThanOrEqualTo("gmt_modified", subscribeTimeEnd);
        }
        example.orderBy("id").asc();
        return example;
    }

    /**
     * 保存发送记录表
     *
     * @param wx48NewsLogSaveRequest
     * @param wx48NewsCrowdRequest
     * @return 返回插入记录表的自增主键
     */
    private Long insertWx48News(Wx48NewsLogSaveRequest wx48NewsLogSaveRequest, Wx48NewsCrowdRequest wx48NewsCrowdRequest, Integer records) {
        Wx48NewsLog wx48NewsLog = BeanConv.copy(wx48NewsLogSaveRequest, Wx48NewsLog.class);
        Date jobTime = wx48NewsLog.getJobTime();
        wx48NewsLog.setSendStartTime(Objects.nonNull(jobTime) ? jobTime : new Date());
        wx48NewsLog.setSendCount(Long.valueOf(records));
        // 判断是否是定时任务
        if (Objects.nonNull(jobTime)) {
            wx48NewsLog.setStatus(SendLogStatusEnum.await.getCode());
        } else {
            wx48NewsLog.setStatus(SendLogStatusEnum.pushing.getCode());
        }
        // 发送条件
        if (Objects.nonNull(wx48NewsCrowdRequest)) {
            wx48NewsLog.setSendCondition(JSONObject.toJSONString(wx48NewsCrowdRequest));
        }
        wx48NewsLogRepository.saveSelective(wx48NewsLog);
        return wx48NewsLog.getId();
    }

    @Override
    public Wx48NewsLogPageResult pageQueryNewsLog(Wx48NewsLogPageQueryRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);
        PageInfo<Wx48NewsLog> pageInfo = wx48NewsLogRepository.pageQueryByRequest(request);
        long total = pageInfo.getTotal();
        Wx48NewsLogPageResult result = RpcResultBuilder.succPageResult(Wx48NewsLogPageResult.class, pageInfo.getPageNum(), pageInfo.getPageSize(), Math.toIntExact(total));
        if (total > 0) {
            List<Wx48NewsLogDTO> logDTOList = BeanConv.copy(pageInfo.getList(), Wx48NewsLogDTO.class);
            if (!CollectionUtils.isEmpty(logDTOList)) {
                for (Wx48NewsLogDTO wx48NewsLogDTO : logDTOList) {
                    Long newsId = wx48NewsLogDTO.getNewsId();
                    Wx48NewsInfo newsInfo = wx48NewsInfoRepository.queryById(newsId);
                    if (Objects.nonNull(newsInfo)) {
                        // 推文json数据-获取推文篇数
                        String xmlContent = newsInfo.getXmlContent();
                        if (StringUtils.isNotBlank(xmlContent)) {
                            try {
                                NewsMessage newsMessage = JSON.parseObject(xmlContent, NewsMessage.class);
                                List<Article> articles = newsMessage.getNews().getArticles();
                                if (!CollectionUtils.isEmpty(articles)) {
                                    wx48NewsLogDTO.setHeadTitle(articles.get(0).getTitle());
                                    wx48NewsLogDTO.setHeadPicUrl(articles.get(0).getPicurl());
                                    wx48NewsLogDTO.setArticleCount(articles.size());
                                }
                            } catch (Exception e) {
                                LOGGER.error("推文json数据-获取推文篇数异常" + e);
                            }
                        }
                    }
                }
            }
            result.setValue(logDTOList);
        }
        LOGGER.info("result=[{}]", result);
        return result;
    }

    @Override
    public SimpleResult<List<Wx48NewsLogDTO>> queryNewsLog(Wx48NewsLogQueryRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);
        List<Wx48NewsLog> wx48NewsLogs = wx48NewsLogRepository.queryByRequest(request);
        List<Wx48NewsLogDTO> logDTOS = null;
        if (!CollectionUtils.isEmpty(wx48NewsLogs)) {
            logDTOS = BeanConv.copy(wx48NewsLogs, Wx48NewsLogDTO.class);
        }
        return RpcResultBuilder.succSimple(logDTOS);
    }

    @Override
    public BaseResult updateNewsLog(Wx48NewsLogUpdateRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);
        Wx48NewsLog wx48NewsLog = BeanConv.copy(request, Wx48NewsLog.class);
        Wx48NewsLog exist = wx48NewsLogRepository.queryById(wx48NewsLog.getId());
        if (Objects.isNull(exist)) {
            return RpcResultBuilder.fail(Errors.Commons.RECORD_NOT_EXISTS);
        }
        wx48NewsLog.setGmtModified(new Date());
        Integer count = wx48NewsLogRepository.updateSelective(wx48NewsLog);
        return count > 0 ? RpcResultBuilder.succ() : RpcResultBuilder.fail(Errors.Commons.UPDATE_FAILED);
    }

    @Override
    public BaseResult cancelNewsLog(Wx48NewsLogCancelRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);
        Wx48NewsLog exist = wx48NewsLogRepository.queryById(request.getId());
        if (Objects.isNull(exist)) {
            return RpcResultBuilder.fail(Errors.Commons.RECORD_NOT_EXISTS);
        }
        if (!SendLogStatusEnum.await.getCode().equals(exist.getStatus())) {
            return RpcResultBuilder.fail(Errors.Wx48HError.CANNOT_CANCEL_NOT_AWAIT_LOG);
        }
        Wx48NewsLog wx48NewsLogUpdate = new Wx48NewsLog();
        wx48NewsLogUpdate.setId(request.getId());
        wx48NewsLogUpdate.setStatus(SendLogStatusEnum.cancel.getCode());
        wx48NewsLogUpdate.setGmtModified(new Date());
        Integer count = wx48NewsLogRepository.updateSelective(wx48NewsLogUpdate);
        return count > 0 ? RpcResultBuilder.succ() : RpcResultBuilder.fail(Errors.Commons.UPDATE_FAILED);
    }

    @Override
    public BaseResult updateNewsLogAccumulate(Wx48NewsLogUpdateAccumRequest request) throws InvokeServiceException {
        ConditionValidator.validate(request);
        Wx48NewsLog wx48NewsLog = BeanConv.copy(request, Wx48NewsLog.class);
        Wx48NewsLog exist = wx48NewsLogRepository.queryById(wx48NewsLog.getId());
        if (Objects.isNull(exist)) {
            return RpcResultBuilder.fail(Errors.Commons.RECORD_NOT_EXISTS);
        }
        wx48NewsLog.setGmtModified(new Date());
        Integer count = wx48NewsLogRepository.updateNewsLogAccumulate(wx48NewsLog);
        return count > 0 ? RpcResultBuilder.succ() : RpcResultBuilder.fail(Errors.Commons.UPDATE_FAILED);
    }
}
